import sys
import requests

from mongo import MongoService


class ShanBeiWord(object):
    def __init__(self, result, log):
        self.mongo = MongoService()
        self.result = open(result, 'w')
        self.log = open(log, 'w')

    def word_detail(self, word):
        word_detail = mongo.find_word(word)
        get_data = {'type': 'yes', 'vocabulary_id': word_detail['content_id']}
        res = requests.get("https://api.shanbay.com/bdc/example/",
                           params=get_data)
        self.result.write(f"{word}: {res.text}\n")

        log = ""
        res_json = res.json()
        if res_json['status_code'] == 0:
            self.mongo.save_example(res_json['data'])
        else:
            log = f"[ERROR] word {word} not save: {res.text}\n"

        log += f"[LOG] {word}: {res.status_code} - {res_json['msg']}"
        self.log.write(log + "\n")
        print(log)


mongo = MongoService()
word_list = mongo.word_list()

shanbei = ShanBeiWord(sys.argv[1], sys.argv[2])
for word in word_list:
    if not word:
        continue
    shanbei.word_detail(word)
